
import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class Login extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
      title: '登录界面',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('登录'),
        ),
        body: new SingleChildScrollView(
          child: new LoginPage(),
        ),
      ),
    );
  }

}

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new LoginState();
  }

}

class LoginState extends State {

  String _phoneNum;
  String _verryCode;



  void login() {

    debugPrint("LoginState -> _phoneNum ->  $_phoneNum ---- _verryCode -> $_verryCode");

    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return new AlertDialog(
          title: new Text('提示'),
          content: new SingleChildScrollView(
            child: new Text("登录成功\n手机号：$_phoneNum\n验证码：$_verryCode")
          ),
          actions: <Widget>[
            new FlatButton(
              child: new Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    ).then((val) {
      print(val);
    });
  }

  void _handlePhoneNumChange(String phoneNum) {

    setState(() {
      _phoneNum = phoneNum;
    });
  }

  void _handleVerryCodeChange(String verryCode) {

    setState(() {
      _verryCode = verryCode;
    });

  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Container(
      margin: const EdgeInsets.fromLTRB(16, 0, 16, 0),
      child: new Column(
        children: <Widget>[
          const SizedBox(height: 30),

          new Align(
            alignment: Alignment.centerLeft,
            child: const Text(
              '手机快捷登录',
              textAlign: TextAlign.left,
              style: TextStyle(
                fontSize: 24.0,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
          ),
          const SizedBox(height: 10),
          new Align(
            alignment: Alignment.centerLeft,
            child: const Text(
              '未注册过的手机号将自动创建账号',
              textAlign: TextAlign.left,
              style: TextStyle(
                fontSize: 14.0,
                color: Colors.grey,
              ),
            ),
          ),
          const SizedBox(height: 20),

          new Align(
            alignment: Alignment.centerLeft,
            child: new AccountWidget(
              phoneNum: _phoneNum,
              onChanged: _handlePhoneNumChange,
            ),
          ),

          const SizedBox(height: 10),

          new Align(
            alignment: Alignment.centerLeft,
            child: new VerificationCodeWidget(
              onChanged: _handleVerryCodeChange,
            ),
          ),
          const SizedBox(height: 10),

          new Align(
            alignment: Alignment.centerLeft,
            child: const Text(
              '已同意并阅读以下协议',
              textAlign: TextAlign.left,
              style: TextStyle(
                fontSize: 14.0,
                color: Colors.grey,
              ),
            ),
          ),

          new Align(
            alignment: Alignment.centerLeft,
            child: RichText(
              text: TextSpan(
                text: '注册/登录即代表同意',
                style: TextStyle(
                  fontSize: 14.0,
                  color: Colors.grey,
                ),
                children: <TextSpan>[
                  TextSpan(
                      text: '《某某协议》',
                      style: TextStyle(
                        color: Colors.blue,
                        fontSize: 18,
                        decoration: TextDecoration.underline,
                      ),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          debugPrint("点击了某某协议");
                        },
                  ),
                  TextSpan(text: '及'),
                  TextSpan(
                      text: '《某某用户协议》',
                      style: TextStyle(
                        color: Colors.blue,
                        fontSize: 18,
                        decoration: TextDecoration.underline,
                      ),
                      recognizer: TapGestureRecognizer()
                        ..onTap = (){
                          debugPrint("点击了某某用户协议");
                        },
                  ),
                ],
              )
            ),
          ),

          const SizedBox(height: 50),
          FlatButton(
            color: (_phoneNum != null && _phoneNum.length >= 11 && _verryCode != null  && _verryCode.length >= 4) ? Colors.blue : Colors.grey,
            onPressed: () {
              /*...*/
              print("点击了同意协议并登录");
              if(_phoneNum == null || _phoneNum.length < 11 || _verryCode == null  || _verryCode.length < 4) {
                return;
              }
              login();
            },
            textColor: Colors.white,
            child: Container (
              margin: const EdgeInsets.fromLTRB(16, 0, 16, 0),
              height: 48.0,
              child: new Align(
                alignment: Alignment.center,
                child: Text(
                  "同意协议并登录",
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

class AccountWidget extends StatefulWidget {



  AccountWidget({Key key,this.phoneNum: "", @required this.onChanged}):super(key: key);

  final String phoneNum;
  final ValueChanged<String> onChanged;
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new AccountState();
  }

}

class AccountState extends State<AccountWidget> {


  bool isCountDown = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  void getVerryCode() {
    if(isCountDown) {
      return;
    }else if(widget.phoneNum == null ) {

      final snackBar = new SnackBar(content: new Text('手机号不能为空'));

      Scaffold.of(context).showSnackBar(snackBar);
      return;
    } else if (widget.phoneNum.length < 11) {
      final snackBar = new SnackBar(content: new Text('手机号位数不能小于11位'));

      Scaffold.of(context).showSnackBar(snackBar);
      return;
    }

    countdown();
  }

  Timer countdownTimer;

  int countdownTime = 60;

  void countdown(){
    countdownTimer =  new Timer.periodic(new Duration(seconds: 1), (timer) {
      debugPrint("倒计时：${timer.tick}");
      if(timer.tick >= 60) {
        timer.cancel();

        countdownTime = 60;
        isCountDown = false;
      } else {
        countdownTime --;
        isCountDown = true;
      }
      setState(() {
        countdownTime = countdownTime;
        isCountDown = isCountDown;
      });
      debugPrint("倒计时：countdownTime-->$countdownTime");
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if(countdownTimer != null) {
      countdownTimer.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Container(
      height: 60,
      decoration: BoxDecoration(
          border:Border(bottom:BorderSide(width: 1,color: Color(0xffe5e5e5)) )
      ),
      child: new Row(
        children: <Widget>[
          Expanded(
            child: TextField(
              decoration: InputDecoration(
                  hintText: '请输入手机号',
                  hintStyle: TextStyle(
                    fontSize: 16.0
                  ),
                  border: InputBorder.none,
              ),
              style: TextStyle(
                fontSize: 16.0
              ),
              keyboardType: TextInputType.number,
              inputFormatters: [
                WhitelistingTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(11)
              ],
              onChanged: (text) {
                debugPrint("onChanged手机号：$text");

                widget.onChanged(text);
              },
              onSubmitted: (text) {
                debugPrint("onSubmitted手机号：$text");
                widget.onChanged(text);
              },
            ),
          ),
          FlatButton(
            onPressed: () {
              /*...*/
              debugPrint("获取验证码");
              getVerryCode();


            },
            child: Text(
              countdownTime == 60 ? "获取验证码" : "${countdownTime}S",
              style: TextStyle(
                fontSize: 16.0,
                color: isCountDown ? Colors.grey : Colors.black
              ),

            ),
          )
        ],
      ),
    );
  }
}

class VerificationCodeWidget extends StatefulWidget {

  VerificationCodeWidget({Key key, @required this.onChanged}):super(key: key);

  final ValueChanged<String> onChanged;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new VerificationCodeState();
  }

}

class VerificationCodeState extends State<VerificationCodeWidget> {

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Container(
      height: 60,
      decoration: BoxDecoration(
          border:Border(bottom:BorderSide(width: 1,color: Color(0xffe5e5e5)) )
      ),
      child: TextField(
          decoration: InputDecoration(
            hintText: '请输入验证码',
            hintStyle: TextStyle(
                fontSize: 16.0
            ),
            border: InputBorder.none,
          ),
          style: TextStyle(
              fontSize: 16.0
          ),
          keyboardType: TextInputType.number,
          inputFormatters: [
            WhitelistingTextInputFormatter.digitsOnly,
            LengthLimitingTextInputFormatter(6)
          ],
          onChanged: (text) {
            debugPrint("onChanged手机号：$text");
            widget.onChanged(text);
          },
          onSubmitted: (text) {
            debugPrint("onSubmitted手机号：$text");
            widget.onChanged(text);
          },
        ),
    );
  }

}


